/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define THREADNUM 10

using namespace std;

pthread_rwlock_t rwlock;

void* readers(void* arg){
    pthread_rwlock_rdlock(&rwlock);
    printf("reader %ld got the lock\n", (long)arg);
    pthread_rwlock_unlock(&rwlock);
    pthread_exit((void*)0); 
}

void* writers(void* arg){
    pthread_rwlock_wrlock(&rwlock);
    printf("writer %ld got the lock\n", (long)arg);
    pthread_rwlock_unlock(&rwlock);
    pthread_exit((void*)0); 
}
int main(){
    int ret, i;
    pthread_t writer_id, reader_id;
    pthread_attr_t attr;
    int nr = 1, nw = 1;
    ret = pthread_rwlock_init(&rwlock, NULL);
    if(ret){
        fprintf(stderr, "init lock failed!\n");
        return ret;
    }

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    for(i = 0; i < THREADNUM; i++){
        if(1){
            pthread_create(&reader_id, &attr, readers, (void*)nr);
            printf("create reader %d\n", nr++);
        }
        else{
            pthread_create(&writer_id, &attr, writers, (void*)nw);
            printf("create writer %d\n", nw++);
        }
    }
    sleep(10);
    return 0;
}